package com.tgy.JUC.Help;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/***
 * @ClassName: CyclicBarrierTest
 * @Description:
 * @Auther: 送你一块二向箔
 * @Date: 15:43 2022/3/11
 * @version : V1.0
 */
public class CyclicBarrierTest {
    public static void main(String[] args) {
        run();
    }

    public static void run() {
        // 集齐七颗龙珠召唤神龙
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {// 如果计数器为7，线程只有6个，则会等待，不进行召唤神龙
            System.out.println("召唤神龙");
        });
        for (int i = 0; i < 7; i++) {
            //中间变量 这里jdk8优化了，不用显示的加fainal
            final int temp = i;
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "收集" + temp + "个龙珠！");
                try {
                    TimeUnit.SECONDS.sleep(3);//这里会等计数器算完才会睡眠
                    //执行加一操作
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
